from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, EmptyPage
from .models import Article
from django.http import HttpResponse
from django.shortcuts import render,HttpResponse,redirect
from django.shortcuts import get_object_or_404

import hashlib
import json
import datetime

def article_list(request):
    # 获取所有未软删除的文章
    articles = Article.objects.filter(delete_time=0)
    
    # 构造文章列表数据
    data = []
    for article in articles:
        article_data = {
            'id': article.id,
            'title': article.title,
            'content': article.content,
            'create_time': timestamp_to_datetime(article.create_time),
            'update_time': timestamp_to_datetime(article.update_time),
        }
        data.append(article_data)
    
    # 返回文章列表数据
    return JsonResponse(data, safe=False)


def article_page(request):
    # 获取所有未软删除的文章
    articles = Article.objects.filter(delete_time=0)
    
    # 创建分页器对象，每页显示10条数据
    paginator = Paginator(articles, 10)
    
    # 获取页码参数，默认为1
    page_number = request.GET.get('page', 1)
    
    try:
        # 获取指定页码的文章列表
        page_articles = paginator.page(page_number)
    except EmptyPage:
        # 如果页码超出范围，返回空列表
        page_articles = []
    
    # 构造文章列表数据
    data = []
    for article in page_articles:
        article_data = {
            'id': article.id,
            'title': article.title,
            'content': article.content,
            'create_time': timestamp_to_datetime(article.create_time),
            'update_time': timestamp_to_datetime(article.update_time),
        }
        data.append(article_data)
    
    # 返回文章列表数据
    return JsonResponse(data, safe=False)


def article_detail(request, article_id):
    article = Article.objects.get(pk=article_id)

    data = {
        'article_id': article.id,
        'title': article.title,
        'content': article.content,
        'create_time': datetime.datetime.fromtimestamp(article.create_time).strftime('%Y-%m-%d %H:%M:%S') if article.create_time else '',
        'update_time': datetime.datetime.fromtimestamp(article.update_time).strftime('%Y-%m-%d %H:%M:%S') if article.update_time else '',
        'delete_time': datetime.datetime.fromtimestamp(article.delete_time).strftime('%Y-%m-%d %H:%M:%S') if article.delete_time else ''
    }
    
    return JsonResponse(data)

def article_create(request):
    # 处理POST请求
    if request.method == 'POST':

        # 获取GET请求中的参数
        get_params = request.GET.dict()
        # 获取POST请求中的参数
        post_params = request.POST.dict()
        
        # 合并GET和POST参数
        all_params = {**get_params, **post_params}
        title = all_params['title']
        content = all_params['content']
        tag = all_params['tag']

        # 检查参数是否都存在
        if title and content:
    
            # 这里可以将参数保存到数据库中，执行其他逻辑等
            # 创建模型实例并保存到数据库
            new_article = Article(title=title, content=content, tag=tag)
            new_article.save()

            # 更新时间字段
            current_time = int(datetime.datetime.now().timestamp())
            new_article.create_time = current_time
            new_article.update_time = current_time
            new_article.save()
            
            # 返回成功的 JSON 响应
            data = {
                'message': 'Submission successful',
                'title': title,
                'content': content,
                'tag': tag,
                'create_time': new_article.create_time
            }

            return JsonResponse(data)
        else:
            # 如果参数不完整，返回错误的JSON响应
            error_data = {'error': 'Missing title or content in the request2'}
            return JsonResponse(all_params, status=400)
        
    # 如果请求方法不是POST，返回405 Method Not Allowed
    else:
        return JsonResponse({'error': 'Method not allowed'}, status=405)

def article_update(request):
    # 处理POST请求
    if request.method == 'POST':

        # 获取GET请求中的参数
        get_params = request.GET.dict()
        # 获取POST请求中的参数
        post_params = request.POST.dict()
        
        # 合并GET和POST参数
        all_params = {**get_params, **post_params}
        article_id = all_params.get('id', None)
        title = all_params.get('title', None)
        content = all_params.get('content', None)
        
        # 检查参数是否都存在
        if title and content:
            # 获取要更新的文章
            article = get_object_or_404(Article, pk=article_id)
            
            # 更新文章的标题、内容和更新时间字段
            article.title = title
            article.content = content
            article.update_time = int(datetime.datetime.now().timestamp())
            article.save()
            
            # 返回成功的 JSON 响应
            data = {
                'message': 'Update successful',
                'article_id': article_id,
                'title': title,
                'content': content,
                'update_time': article.update_time
            }
            return JsonResponse(data)
        else:
            # 如果参数不完整，返回错误的 JSON 响应
            error_data = {'error': 'Missing title or content in the request'}
            return JsonResponse(error_data, status=400)
    else:
        # 如果请求方法不是 POST，返回 405 Method Not Allowed
        return JsonResponse({'error': 'Method not allowed'}, status=405)
    

def article_delete(request):
    # 处理 DELETE 请求
    if request.method == 'DELETE':

        # 获取GET请求中的参数
        get_params = request.GET.dict()
        # 获取POST请求中的参数
        post_params = request.POST.dict()
        
        # 合并GET和POST参数
        all_params = {**get_params, **post_params}
        article_id = all_params.get('id', None)
        m_param = all_params.get('m', None)

        # 获取要删除的文章
        article = get_object_or_404(Article, pk=article_id)
        
        if m_param == 'true':
            # 真正删除文章
            article.delete()
        else:
            # 更新 delete_time 字段为当前系统时间戳
            article.soft_delete()
        
        # 返回成功的 JSON 响应
        data = {
            'message': 'Article soft-deleted successfully',
            'article_id': article_id
        }
        return JsonResponse(data)
    else:
        # 如果请求方法不是 DELETE，返回 405 Method Not Allowed
        return JsonResponse({'error': 'Method not allowed'}, status=405)
    

def timestamp_to_datetime(timestamp):
    # 如果时间戳为0，则返回空字符串
    if timestamp == 0:
        return ''
    # 将时间戳转换为 datetime 对象
    dt_object = datetime.datetime.fromtimestamp(timestamp)
    # 将 datetime 对象格式化为指定格式的字符串
    formatted_datetime = dt_object.strftime('%Y-%m-%d %H:%M:%S')
    return formatted_datetime